import json
import random
import time
import uuid
import urllib.parse
import re
import threading
import base64
from io import BytesIO
import requests

def record_time(func):
    def record_fun(*args, **kwargs):
        t0 = time.time()
        result = func(*args, **kwargs)
        print('time cost: {}s'.format(round(time.time() - t0, 4)),end="\t")
        return result
    return record_fun


class BaserUtil:
    def __init__(self):
        pass

    def group_list_by_count(self,lst, group_count=None, elements_per_group=None):
        if group_count is not None:
            # 计算每个组应该包含的元素个数
            count_per_group, remainder = divmod(len(lst), group_count)
            # 创建一个包含group_count个空列表的列表，用于存放分组后的结果
            grouped_lst = [[] for _ in range(group_count)]
            # 将元素按照计算得到的每组元素个数分组
            start = 0
            for i in range(group_count):
                group_size = count_per_group + (1 if i < remainder else 0)
                grouped_lst[i] = lst[start:start + group_size]
                start += group_size
        elif elements_per_group is not None:
            # 计算总共要分成几组
            group_count, remainder = divmod(len(lst), elements_per_group)
            if remainder > 0:
                group_count += 1
            # 创建一个包含group_count个空列表的列表，用于存放分组后的结果
            grouped_lst = [[] for _ in range(group_count)]
            # 将元素按照指定的每组元素个数分组
            start = 0
            for i in range(group_count):
                grouped_lst[i] = lst[start:start + elements_per_group]
                start += elements_per_group
        else:
            return None

        return grouped_lst


    def generate_random_num(self,min_value=1,max_value=3):
        # 生成一个随机整数
        randint = random.randint(min_value, max_value)
        # 生成一个随机小数
        uniform = random.uniform(0, 1)
        return randint+uniform

    def generate_random_int_num(self, min_value=1, max_value=3):
        # 生成一个随机整数
        randint = random.randint(min_value, max_value)
        return randint

    def sleep_period_time(self,min_value=1,max_value=3):
        time.sleep(self.generate_random_num(min_value,max_value))

    def sleep(self,long):
        time.sleep(long)

    def generateUuid(self):
        id = str(uuid.uuid4())
        return str.replace(id, "-", "", -1)

    def generate_spend_max_time(self,max_value,down=0,up=100):
        spend_max_time = max_value - random.randint(down, up)
        return abs(spend_max_time)


    def remove_whitespace(self,string):
        return re.sub(r'\s', '', string)

    def urlencode(self,str):
        return urllib.parse.quote(str)

    #对字母以及数字之外的字符进行编码
    def urlencode2(self, str):
        return urllib.parse.quote(str)

    def urldecode(self,str):
        return urllib.parse.unquote(str)

    def url2_rawurl(self,url):
        parsed_url = urllib.parse.urlparse(url)
        raw_url = parsed_url.scheme + parsed_url.netloc + parsed_url.path
        return raw_url

    def obj2str(self,obj):
        json_str = json.dumps(obj, ensure_ascii=False)
        return json_str

    def str2obj(self,text):
        obj = json.loads(text,encoding='utf8')
        return obj

    def async_run(self,func, args_):
        t0 = time.time()
        # 创建线程列表
        threads = []
        for args in args_:
            thread = threading.Thread(target=func, args=args)
            threads.append(thread)
            thread.start()
        # 等待所有线程完成
        for thread in threads:
            thread.join()
        print(f'异步执行完成   time cost: {round(time.time() - t0, 4)}s')

    def ocr(self,data,headers={}):
        url = "https://www.paddlepaddle.org.cn/paddlehub-api/image_classification/chinese_ocr_db_crnn_mobile"
        response = requests.post(url, json=data,headers=headers)
        response.encoding = 'utf-8'
        resp_content = response.text
        return self.str2obj(resp_content)

    def paddle_ocr(self,base64_data=None,image_path=None):
        key="image"
        data = {}
        if base64_data!=None:
            data[key]=self.extract_longest_base64_from_text(base64_data)
            return self.ocr(data)
        if image_path!=None:
            base64_data=self.image_to_base64(image_path)
            data[key]=base64_data
            return self.ocr(data)

    def extract_longest_base64_from_text(self,text):
        pattern = re.compile(r"(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?")
        base64_strings = re.findall(pattern, text)
        longest_base64_string = max(base64_strings, key=len, default=None)
        return longest_base64_string

    def has_chinese_character(self,text):
        pattern = re.compile(u'[\u4e00-\u9fa5]')
        return bool(pattern.search(text))

    def contains_number(self,string):
        for char in string:
            if char.isnumeric():
                return True
        return False


    def random_skip_n_characters(self,text, n,radom_flag=True):
        if n >= len(text):
            return ""
        if radom_flag==False:
            return text[0:n]
        skip_indices = random.sample(range(len(text)), n)
        skip_indices.sort(reverse=True)
        for index in skip_indices:
            text = text[:index] + text[index + 1:]
        return text

    def sort_collect(self,lst,sort_key,reverse=False):
        if lst==None:
            return []
        if len(lst)<=1:
            return lst
        sorted_list = sorted(lst, key=lambda x: x[sort_key], reverse=reverse)
        return sorted_list

    def deduplicate_dict_list(self,dict_list, key):
        seen = set()
        deduplicated_list = []
        for dict_item in dict_list:
            if dict_item[key] not in seen:
                seen.add(dict_item[key])
                deduplicated_list.append(dict_item)
        return deduplicated_list

    # 求最大相同个数
    def find_max_common_items(self,lists):
        min_len = 1000000
        for lst in lists:
            if len(lst) < min_len:
                min_len = len(lst)
        seek = min_len
        while seek > 0:
            # 将各个列表转换为集合
            sets = [set(lst[:seek]) for lst in lists]
            # 计算交集
            intersection = set.intersection(*sets)
            # 返回交集的长度
            if seek == len(intersection):
                return seek
            seek -= 1
        return -1

    def is_empty(self,obj):
        return  obj==None or len(obj)==0


if __name__ == "__main__":
    this = BaserUtil()
    base64_data=' '

    text = this.extract_longest_base64_from_text(base64_data)
    this.base64_to_image(text,image_path="./156263.gif")
